<template>
  <el-row :gutter="20">
    <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="5" class="mb-3">
      <el-card class="el-card">
        <div slot="header">
          <span>个人信息</span>
        </div>
        <div>
          <div class="mt-5 mb-3 text-center">
            <el-avatar
              :size="100"
              :key="adminInfo.profile_photo"
              :src="adminInfo.profile_photo"
            />
          </div>
          <el-form label-width="80" size="small">
            <el-form-item label="用户账号：">
              <span>{{ adminInfo.username }}</span>
            </el-form-item>
            <el-form-item label="用户昵称：">
              <span>{{ adminInfo.nickname }}</span>
            </el-form-item>
            <el-form-item label="用户邮箱：">
              <span>{{ adminInfo.email }}</span>
            </el-form-item>
            <el-form-item label="用户电话：">
              <span>{{ adminInfo.phone }}</span>
            </el-form-item>
            <el-form-item label="用户备注：">
              <span>{{ adminInfo.note }}</span>
            </el-form-item>
            <el-form-item label="创建时间：">
              <span>{{ adminInfo.create_time }}</span>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-col>
    <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="19">
      <el-card class="el-card">
        <div slot="header">
          <span>基本资料</span>
        </div>
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本资料" name="first">
            <el-form
              ref="personalFormRef"
              :model="personalParams"
              :rules="personalParamsRules"
              label-width="100px"
            >
              <el-form-item label="用户头像" prop="profile_photo">
                <el-upload
                  :headers="headers"
                  class="relative w-20 h-20 truncate border border-dashed rounded-md cursor-pointer border-inherit"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                >
                  <el-avatar
                    :size="78"
                    shape="square"
                    :src="personalParams.profile_photo"
                    alt="用户头像"
                    title="点击更换头像"
                  />
                </el-upload>
              </el-form-item>
              <el-form-item label="用户账号" prop="username">
                <el-input
                  v-model="personalParams.username"
                  placeholder="请输入用户账号"
                />
              </el-form-item>
              <el-form-item label="用户昵称" prop="nickname">
                <el-input
                  v-model="personalParams.nickname"
                  placeholder="请输入用户昵称"
                />
              </el-form-item>
              <el-form-item label="用户电话" prop="phone">
                <el-input
                  v-model="personalParams.phone"
                  placeholder="请输入用户电话"
                />
              </el-form-item>
              <el-form-item label="用户邮箱" prop="email">
                <el-input
                  v-model="personalParams.email"
                  placeholder="请输入用户邮箱"
                />
              </el-form-item>
              <el-form-item label="用户备注" prop="note">
                <el-input
                  v-model="personalParams.note"
                  placeholder="请输入用户备注"
                  type="textarea"
                  rows="3"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  v-if="hasPermission('api.sysAdmin.updatePersonal')"
                  type="primary"
                  @click="savePersonalInfo"
                >
                  确认
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="second">
            <el-form
              ref="personalPasswordFormRef"
              :rules="personalPasswordParamsRules"
              :model="personalPasswordParams"
              label-width="100px"
            >
              <el-form-item label="旧密码" prop="password">
                <el-input
                  type="password"
                  v-model="personalPasswordParams.password"
                  placeholder="请输入旧密码"
                  show-password
                />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  type="password"
                  v-model="personalPasswordParams.newPassword"
                  placeholder="请输入新密码"
                  show-password
                />
              </el-form-item>
              <el-form-item label="确认密码" prop="resetPassword">
                <el-input
                  type="password"
                  v-model="personalPasswordParams.resetPassword"
                  placeholder="请确认密码"
                  show-password
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  v-if="hasPermission('api.sysAdmin.updatePersonalPassword')"
                  type="primary"
                  @click="savePersonalPassword"
                >
                  确认
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import {
  PersonalParams,
  PersonalPasswordParams,
} from '@/api/auth/model/adminModel'
import { updateParsonal, updateParsonalPassword } from '@/api/auth/admin'
import { LoginStore } from '@/store/login'
import { FormInstance, FormRules } from 'element-plus'
import { useForm } from '@/hooks'
import router from '@/router'
import { usePermission } from '@/hooks/permission'

const { validate } = useForm()
const { hasPermission } = usePermission()
const adminInfoStore = LoginStore()

const adminInfo = computed(() => adminInfoStore.sysAdmin)

const headers = ref({
  Authorization: adminInfoStore.token,
})
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_URL
const activeName = ref<string>('first')

const personalFormRef = ref<FormInstance>(null!)

const personalPasswordFormRef = ref<FormInstance>(null!)

let personalParams = reactive<PersonalParams>({
  admin_id: adminInfo.value.admin_id,
  email: adminInfo.value.email,
  nickname: adminInfo.value.nickname,
  note: adminInfo.value.note,
  phone: adminInfo.value.phone,
  profile_photo: adminInfo.value.profile_photo,
  username: adminInfo.value.username,
})

let personalPasswordParams = reactive<PersonalPasswordParams>({
  admin_id: adminInfo.value.admin_id,
  newPassword: '',
  password: '',
  resetPassword: '',
})

const handleAvatarSuccess = (res: any) => {
  if (res.code != 200) {
    ElMessage.error(`${res.message}(文件上传)`)
    return
  }
  personalParams.profile_photo = res.data.url
}

//验证用户名
const validateUserName = (rule: any, value: any, callback: any) => {
  console.log(rule, value, callback)

  if (!new RegExp('^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$').test(value)) {
    rule.message = '用户名不能有特殊字符'
    callback(new Error(rule.message))
  }
  if (/^\d+\d+\d$/.test(value)) {
    rule.message = '用户名不能全为数字'
    callback(new Error(rule.message))
  }
  callback()
}

//验证密码
const validatePassword = (rule: any, value: any, callback: any) => {
  const pwdRegex = new RegExp(
    '(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{6,18}'
  )
  if (!pwdRegex.test(value)) {
    /* eslint-disable-next-line */
    rule.message = '密码中必须包含大小写字母、数字、特殊字符,长度6到18位'
    callback(new Error(rule.message))
  }
  callback()
}

const personalParamsRules = reactive<FormRules<PersonalParams>>({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
    {
      min: 5,
      max: 16,
      message: '用户名长度在5-16个字符',
      trigger: 'blur',
    },
    {
      validator: validateUserName,
      message: '用户名仅字母、数字和下划线组成的5-16位字符',
      trigger: 'blur',
    },
  ],
  nickname: {
    required: true,
    message: '请输入昵称',
    trigger: 'blur',
  },
  email: {
    required: true,
    message: '请输入邮箱',
    trigger: 'blur',
  },
  phone: {
    required: true,
    message: '请输入手机号',
    trigger: 'blur',
  },
})

const personalPasswordParamsRules = reactive<FormRules<PersonalPasswordParams>>(
  {
    password: [
      {
        required: true,
        message: '请输入旧密码',
        trigger: 'blur',
      },
      // {
      //   validator: validatePassword,
      //   message: '密码中必须包含大小写字母、数字、特殊字符,长度6到18位',
      //   trigger: 'blur',
      // },
    ],
    newPassword: [
      {
        required: true,
        message: '请输入新密码',
        trigger: 'blur',
      },
      {
        validator: validatePassword,
        message: '密码中必须包含大小写字母、数字、特殊字符,长度6到18位',
        trigger: 'blur',
      },
    ],
    resetPassword: [
      {
        required: true,
        message: '请输入确认密码',
        trigger: 'blur',
      },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value !== personalPasswordParams.newPassword) {
            rule.message = '两次密码不一致'
            callback(new Error(rule.message))
          }
          callback()
        },
      },
    ],
  }
)

const savePersonalInfo = async () => {
  await validate(personalFormRef.value)
  const { code, message } = await updateParsonal(personalParams)
  if (code != 200) {
    ElMessage.error(message)
    return
  }
  ElMessage.success(message)
  adminInfoStore.setValue('sysAdmin', {
    admin_id: adminInfo.value.admin_id,
    create_time: adminInfo.value.create_time,
    dept_id: adminInfo.value.dept_id,
    email: personalParams.email,
    nickname: personalParams.nickname,
    note: personalParams.note,
    password: adminInfo.value.password,
    phone: personalParams.phone,
    post_id: adminInfo.value.post_id,
    profile_photo: personalParams.profile_photo,
    status: adminInfo.value.status,
    username: personalParams.username,
  })
}
const savePersonalPassword = async () => {
  await validate(personalPasswordFormRef.value)
  const { code, message } = await updateParsonalPassword(personalPasswordParams)
  if (code != 200) {
    ElMessage.error(message)
    return
  }
  adminInfoStore.cleanLoginInfo()
  ElMessage.success('修改成功')
  router.replace({ path: '/login' })
}
</script>

<style scoped></style>
